package edu.kaifadui.lmbase.controller;

import edu.kaifadui.lmbase.jwt.TokenUtil;
import edu.kaifadui.lmbase.pojo.Dev;
import edu.kaifadui.lmbase.service.DevService;
import edu.kaifadui.lmbase.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 陈世杰
 * @since 2022-02-22
 */
@RestController
@RequestMapping("/dev")
public class DevController {

    @Autowired
    private DevService devService;
    @Autowired
    private TokenUtil tokenUtil;

    @Value("${get.dev.secret}")
    private String secret;

    @GetMapping("/dev/{code}")
    Result addDev(@PathVariable String code){
        if (!code.equals(secret)){
            return new Result(0,"非法访问,已上报报警处理");
        }
        UUID generated = UUID.randomUUID();
        String uuid = generated.toString().replace("-", "");
        Dev dev = new Dev();
        dev.setAppsecret(uuid);
        if(devService.save(dev)){
            Map<String, Object> map = new HashMap<>(1);
            map.put("appsecret",uuid);
            List<Dev> devs = devService.listByMap(map);
            if (!CollectionUtils.isEmpty(devs)){
                return new Result(200,devs.get(0),"创建成功，请保存好app key和app secret，本系统不负责保存，如丢失请到开发队主席出汇报情况并补领");
            }
        }
        return new Result(0,"创建失败,联系主席解决");
    }

    @PostMapping({"/login","/token"})
    Result LoginDev(@RequestBody Dev dev){
        Map<String, Object> map = new HashMap<>(1);
        map.put("appkey",dev.getAppkey());
        List<Dev> devs = devService.listByMap(map);
        if (CollectionUtils.isEmpty(devs)){
            return new Result(0,"用户不存在");
        }
        if (dev.getAppsecret().equals(dev.getAppsecret())){
            String token = tokenUtil.getToken(dev);
            return new Result(200,dev,"成功登录",token);
        }
        return new Result(0,"密码错误");
    }
}

